import router from './router'
import _ from './utils/common'
import storage from 'store'
import store from './stores'
import { ACCESS_TOKEN } from "./stores/types";
import notification from 'ant-design-vue/es/notification'

const defaultRoutePath = '/'
const loginRoutePath = '/login'
const whiteList = ['login', 'register']

router.beforeEach((to, from, next) =>{
  _.TopLoadingStart()
  if (storage.get(ACCESS_TOKEN)) {
    if (to.path === loginRoutePath) {
      const redirect = to.query.redirect
      if (redirect !== 'undefined') {
        // 重定向
        next({ path: redirect })
      } else {
        // 默认页面
        next({ path: defaultRoutePath })
      }
    } else {
      // 拉去用户信息
      store.dispatch('GetInfo')
        .then(() => {
          store.dispatch('GetMenuRights').then(() =>{
            next()
          })
        }).catch(() => {
          //
        notification.error({
          message: '错误',
          description: '请求用户信息失败，请登录重试'
        })
        // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
        store.dispatch('Logout').then(() => {
          next({ path: loginRoutePath, query: { redirect: to.fullPath } })
        })
      })
    }
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
    }
  }
  document.title = '个体户-' + to.meta.title
})

router.afterEach((to,from) => {
  _.TopLoadingFinish()
})
